<template>
  <el-form-item label="浏览权限" prop="browseRule">
    <el-tree-select
      v-model="selectRuleId"
      :data="brandList"
      :props="defaultProps"
      :multiple="multiple"
      :show-checkbox="multiple"
      clearable
      class="w-280px!"
      node-key="id"
      placeholder="请选择浏览权限"
      :disabled="isDetail"
    />
    <el-button text type="primary" @click="createRule"> 新增</el-button>
  </el-form-item>
  <BrowseRule v-if="selectRuleId" v-model="selectRuleId" :is-detail="true" />
  <BrowseRuleForm ref="BrowseRuleFormRef" @success="setSelectRuleId" />
</template>
<script lang="ts" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as ProductBrandApi from '@/api/mall/product/brand'
import { BrandVO } from '@/api/mall/product/brand'
import { oneOfType } from 'vue-types'
import { propTypes } from '@/utils/propTypes'
import BrowseRule from './BrowseRule.vue'
import BrowseRuleForm from './BrowseRuleForm.vue'
/** 商品规则选择组件 */
defineOptions({ name: 'BorwseRuleSelect' })

const props = defineProps({
  // 选中的ID
  modelValue: oneOfType<number | number[]>([Number, Array<Number>]),
  // 是否多选
  multiple: propTypes.bool.def(false),
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

/** 选中的 ID */
const selectRuleId = computed({
  get: () => {
    return props.modelValue
  },
  set: (val: number | number[]) => {
    emit('update:modelValue', val)
  }
})
/** 新增规则 */
const BrowseRuleFormRef = ref()
const createRule = () => {
  BrowseRuleFormRef.value.open('create')
}
/**设置选择的规则ID */
const setSelectRuleId = (id) => {
  selectRuleId.value = id
}
/** 分类选择 */
const emit = defineEmits(['update:modelValue'])
/** 初始化 **/
const brandList = ref<BrandVO[]>([]) // 商品规则列表
onMounted(async () => {
  // 获得分类树
  const data = await ProductBrandApi.getSimpleBrandList()
  brandList.value = handleTree(data, 'id', 'parentId')
})
</script>
